//
//  SY_Par_CurAttendanceViewController.m
//  ChatDemo-UI2.0
//
//  Created by zz on 17/2/20.
//  Copyright © 2017年 zz. All rights reserved.
//

#import "SY_Par_CurAttendanceViewController.h"
#import "ParLeaCountTableViewCell.h"
#import "SYPickerView.h"
#import "HomeParLeaveDetailController.h"

@interface SYLeaveListCell : UITableViewCell

@property (nonatomic,strong) UILabel *leftLabel;
@property (nonatomic,strong) UILabel *rightLabel;

@end

@implementation SYLeaveListCell : UITableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        _leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 14, 250, 16)];
        _leftLabel.font = [UIFont systemFontOfSize:15];
        _leftLabel.textColor = [UIColor colorWithHexString:@"#3b3b3b"];
        [self.contentView addSubview:_leftLabel];
        
        _rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREENWIDTH - 27 - 100, 14, 100, 16)];
        _rightLabel.font = [UIFont systemFontOfSize:15];
        _rightLabel.textAlignment = NSTextAlignmentRight;
        _rightLabel.textColor = [UIColor colorWithHexString:@"#979797"];
        [self.contentView addSubview:_rightLabel];
        
    }
    
    return self;
}

@end

@interface SY_Par_CurAttendanceViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *table;

@property (nonatomic,strong) NSMutableArray *leaveArray; //请假
@property (nonatomic,strong) NSMutableArray *crunkArray; //旷课

@property (nonatomic,strong) NSDictionary *recodeDict; //统计字典
@end

@implementation SY_Par_CurAttendanceViewController{
    
    NSString * stuId;
    NSString * className;
    NSString * stuName;
    NSString *classId;
    
    NSString *selDate;
    
    
    //记录Picker当前选择的日期
    NSInteger currentPickerIndex;
    NSInteger currentPickerDetailIndex;

}

#pragma mark -Getter
- (UITableView *)table{
    
    if (!_table) {
        
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, VIEW_WIDTH, SCREENHEIGH - SafeAreaTopHeight) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.tableFooterView = [[UIView alloc] init];
        
    }
    
    return _table;
}

- (NSMutableArray *)leaveArray{
    
    if (!_leaveArray) {
        
        _leaveArray = [NSMutableArray array];
    }
    return _leaveArray;
}

- (NSMutableArray *)crunkArray{
    
    if (!_crunkArray) {
        
        _crunkArray = [NSMutableArray array];
    }
    
    return _crunkArray;
}

#pragma mark -LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    NSDictionary *dict = [_studentsArr objectAtIndex:0];
    stuName = [dict objectForKey:@"studentname"];
    stuId = [dict objectForKey:@"studentid"];
    
    NSDictionary *classDict = [[dict objectForKey:@"item"] firstObject];
    className = [classDict objectForKey:@"classname"];
    classId = [classDict objectForKey:@"classid"];

    
    self.navBar.nav_titleLabel.text = @"考勤统计";
    
    [self.view addSubview:self.table];
    
    //获取考勤统计数据
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"yyyy-MM-01"];
    
    [self requestMonthRecod:[formatter stringFromDate:date]];
    
    [self recodeDetailList:[formatter1 stringFromDate:date]];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
}

#pragma mark -UITableViewDataSource &&UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
       
        return 1;
       
    }else if (section == 1){
       
       if (![self.leaveArray isKindOfClass:[NSNull class]]) {
          
          return self.leaveArray.count > 0 ? self.leaveArray.count : 1;
          
       }else
       {
          return 1;
       }
       
       
    }else{
       
        if (![self.crunkArray isKindOfClass:[NSNull class]]) {
           
            return self.crunkArray.count > 0 ? self.crunkArray.count : 1;
        }else{
           
           return 1;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
       
        
        ParLeaCountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];

        
        if (!cell) {
            
            cell = [[ParLeaCountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
            
            [cell.selStuBtn setTitle:[NSString stringWithFormat:@"%@  %@",stuName,className] forState:UIControlStateNormal];
            
            [cell.selStuBtn addTarget:self action:@selector(selStudent:) forControlEvents:UIControlEventTouchUpInside];
            
            //获取当前月份
            NSDate *date = [NSDate date];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy年MM月"];
            
            NSString *dateStr = [formatter stringFromDate:date];
            
            [cell.selDateBtn setTitle:dateStr forState:UIControlStateNormal];
            [cell.selDateBtn addTarget:self action:@selector(selDate:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        if (self.recodeDict) {
            
            cell.recodeDict = self.recodeDict;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else if (indexPath.section == 1){
    
        SYLeaveListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        
        if (!cell) {
            
            cell = [[SYLeaveListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2"];
        }
        
        
        NSDictionary *dict;
       
        if (self.leaveArray.count > 0) {
            
            dict = [self.leaveArray objectAtIndex:indexPath.row];
            cell.leftLabel.text =  [self getProperDate:[dict objectForKey:@"jointime"]];
            cell.rightLabel.text = [dict objectForKey:@"eventname"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }else{
        
            cell.leftLabel.text = @"本月暂无请假记录";
            cell.rightLabel.text = @"";
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else{
    
        SYLeaveListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        
        if (!cell) {
            
            cell = [[SYLeaveListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell4"];
        }
        
        NSDictionary *dict;
        
        if (self.crunkArray.count > 0) {
            
            dict = [self.crunkArray objectAtIndex:indexPath.row];
            cell.leftLabel.text = [self getProperDate:[dict objectForKey:@"jointime"]];
        }else{
            
            cell.leftLabel.text = @"本月暂无旷课记录";
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 26)];
    v.backgroundColor = RGBCOLOR(243, 243, 243);
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 4.5, 100, 15)];
    label.textColor = [UIColor colorWithHexString:@"#1ebfff"];
    label.font = [UIFont systemFontOfSize:14];
    [v addSubview:label];
    if (section == 1) {
        
        label.text = @"请假记录";
        return v;
    }else if(section == 2){
        
        label.text = @"旷课记录";
        return v;
    }
    
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 1 || section == 2) {
        
        return 25;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        return 160;
        
    }else{
    
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        
        if (self.leaveArray.count == 0) {
            return;
        }
        
        
        NSDictionary *dict = [self.leaveArray objectAtIndex:indexPath.row];
        
        NSString *leaveid = [dict objectForKey:@"eventid"];
        
        HomeParLeaveDetailController *vc = [[HomeParLeaveDetailController alloc] init];
        
        vc.leaveid = [leaveid integerValue];
        
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark -Action
- (void)selStudent:(ParAtdselBtn*)sender{
    
    SYPickerView *picker = [[SYPickerView alloc] initWithFrame:CGRectZero];
    picker.pickerMode = SYPickerModeStudent;
    
    picker.indexOfType = currentPickerIndex;
    picker.indexOfDetailType = currentPickerDetailIndex;
    
    picker.sourceArray = _studentsArr;
    
    picker.sureBlock = ^(NSDictionary *dict,NSInteger indexOfType,NSInteger indexOfDetailType){
        
        //给picker赋选中值
        self ->currentPickerDetailIndex = indexOfDetailType;
        self ->currentPickerIndex = indexOfType;

        self->stuName = [dict objectForKey:@"studentname"];
        self->stuId = [dict objectForKey:@"studentid"];
        
        NSArray *arr=[dict objectForKey:@"item"];
        if (arr.count>0) {
            self->className=[[arr objectAtIndex:indexOfDetailType] objectForKey:@"classname"];
            self->classId=[[arr objectAtIndex:indexOfDetailType] objectForKey:@"classid"];
        }
        
        //赋值
        [sender setTitle:[NSString stringWithFormat:@"%@ %@",self->stuName,self->className] forState:UIControlStateNormal];
        
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM"];
        
        if (!self->selDate) {
            
            self->selDate =[formatter stringFromDate:date];
        }
        
        [self requestMonthRecod:self->selDate];
        [self recodeDetailList:self->selDate];
    };
}

- (void)selDate:(ParAtdselBtn*)sender{
    
    SYPickerView *picker = [[SYPickerView alloc] initWithFrame:CGRectZero];
    picker.pickerMode = SYPickerModeMonth;
    
        
    picker.sureBlock = ^(NSDictionary *dict,NSInteger indexOfType,NSInteger indexOfDetailType){
        
        NSString *monthSel = [dict objectForKey:@"month"];
        NSString *yearSel = [dict objectForKey:@"year"];
        
        NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        
        int monthInt =[[monthSel stringByTrimmingCharactersInSet:nonDigits] intValue];
        
        //        int yearInt = [[year stringByTrimmingCharactersInSet:nonDigits] intValue];
        
        NSString *monthStr = [NSString stringWithFormat:@"%02d",monthInt];
        
        NSString *yearStr = [NSString stringWithFormat:@"%ld",(long)[yearSel integerValue]];
        
        NSString *dateStr = [NSString stringWithFormat:@"%@%@",yearSel,monthSel];
        
        [sender setTitle:dateStr forState:UIControlStateNormal];
        
        
        
        NSString *dateSelStr = [NSString stringWithFormat:@"%@-%@",yearStr,monthStr];
        NSDateFormatter *formatter1 =[[NSDateFormatter alloc]init];
        [formatter1 setDateFormat:@"yyyy-MM"];
        
        selDate = dateSelStr;
        
        [self requestMonthRecod:dateSelStr];
        [self recodeDetailList:dateSelStr];
    };
    [picker show];
}

#pragma mark -Action
- (void)requestMonthRecod:(NSString *)dateStr{
    
    BaseModel *param = [BaseModel param];
    
    param.method = @"sy_rollcall_studentrecord";
    param.studentid = stuId;
    param.classid = classId;
    
    param.date = dateStr;
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dict = [[jsonObject objectForKey:@"re_data"] firstObject];
        
        self -> _recodeDict = dict;
        
        [self.table reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)recodeDetailList:(NSString *)dateStr{
    
    //详情必须在结尾传一个01,接口要的,虽然没啥用
//    if (![dateStr hasSuffix:@"-01"]) {  //不能这么判断，2017-01 是一个坑....
//        
//        dateStr = [NSString stringWithFormat:@"%@-01",dateStr];
//    }
    
    if (dateStr.length <= 7 ) {
        dateStr = [NSString stringWithFormat:@"%@-01",dateStr];
    }

    BaseModel *param = [BaseModel param];
    
    param.method = @"api_rollcallmonth_info";
    param.studentid = stuId;
    param.classid = classId;
    param.datetime = dateStr;
    
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {

        NSDictionary *dict = [jsonObject objectForKey:@"re_data"];
       
       id leabeArr = [dict objectForKey:@"leavelist"];
       
       if ([leabeArr isKindOfClass:[NSNull class]]) {
          
          self.leaveArray = nil;
          
       }else{
          
          self.leaveArray = leabeArr;
       }

        id arr = [dict objectForKey:@"kklist"];
        if ([arr isKindOfClass:[NSNull class]]) {
            
            self.crunkArray = nil;
        }else{
        
            self.crunkArray = arr;
        }
        
        [self.table reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        
    }];
}

//转成正确时间字符串
- (NSString *)getProperDate:(NSString *)str{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *date = [formatter dateFromString:str];
    
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    
    
    NSString *newDateStr = [formatter stringFromDate:date];
    
    NSString *weekStr = [Utils weekdayStringFromDate:date];
    
    newDateStr = [NSString stringWithFormat:@"%@ (%@)",newDateStr,weekStr];
    
    return newDateStr;
}

@end
